import { useEffect, useState } from 'react';
import { Stats } from '@react-three/drei';

const PerformanceMonitor = () => {
  const [fps, setFps] = useState(0);
  const [memory, setMemory] = useState({
    used: 0,
    total: 0
  });

  useEffect(() => {
    let frameCount = 0;
    let lastTime = performance.now();

    const measureFPS = () => {
      const currentTime = performance.now();
      frameCount++;

      if (currentTime - lastTime >= 1000) {
        setFps(Math.round((frameCount * 1000) / (currentTime - lastTime)));
        frameCount = 0;
        lastTime = currentTime;
      }

      requestAnimationFrame(measureFPS);
    };

    const measureMemory = async () => {
      if ('memory' in performance) {
        const memory = performance.memory;
        setMemory({
          used: Math.round(memory.usedJSHeapSize / 1048576), // Convert to MB
          total: Math.round(memory.totalJSHeapSize / 1048576)
        });
      }
    };

    const memoryInterval = setInterval(measureMemory, 2000);
    measureFPS();

    return () => {
      clearInterval(memoryInterval);
    };
  }, []);

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      right: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      color: 'white',
      padding: '10px',
      fontSize: '12px',
      zIndex: 1000
    }}>
      <div>FPS: {fps}</div>
      <div>Memory: {memory.used}MB / {memory.total}MB</div>
      <Stats />
            </div>
  );
};

export default PerformanceMonitor;